package com.example.howard.mytcpclient;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;


public class ConnectService extends Service {

    public ClientThread clientThread;
    private ConnectBinder connectBinder = new ConnectBinder();
    private final String TAG = "ConnectService";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    public void connect(String IP, String port) {

        if (null == clientThread) {
            clientThread = new ClientThread(IP, port);
            new Thread(clientThread).start();

        }
    }
    public ClientThread getClientThread(){
        return clientThread;
    }
    //发送消息，给clientThread发送Handler信息
    public boolean sendMsg(String msg) {

        if (null != clientThread) {
            Message message = new Message();
            message.what = 0x852;
            message.obj = msg;
            clientThread.sendHandler.sendMessage(message);
            return true;
        } else {
            return false;
        }
    }

    public void insertReceiverListener(Handler handler) {

        if (null != clientThread) {

            clientThread.setReceiveHandler(handler);
        }
    }

    //断开线程
    public void disconnect() {

        if (null != clientThread) {

            clientThread.disconnect();
            clientThread = null;
        }
    }

    //判断线程状态是否连接
    public boolean isconnect() {
        if (null == clientThread) {
            return false;
        } else
            return true;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return connectBinder;
    }

    public class ConnectBinder extends Binder {
        public ConnectService getService() {
            return ConnectService.this;
        }
    }
}
